package com.truongnha.clienttn.data.sao;

import com.truongnha.clienttn.data.dao.AccountDAO;
import com.truongnha.clienttn.data.dao.CreateDatabase;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.truongnha.clienttn.data.servicehelper.utils;
import com.truongnha.clienttn.presentation.temp.JSONParser;

import config.Url;

public class LoginSAO {
	private Context context;
	static String csrfmiddlewaretoken = "";
	private String url;
	private String userName;
	private String passWord;
	private boolean success = false;
	private static String KEY_SUCCESS = "success";
	private static String KEY_FIRST_NAME = "firstName";
	private static String KEY_LAST_NAME = "lastName";
	private static String KEY_TYPE = "type";// 0- student, 3- teacher
	private static String KEY_CLASS = "class";
	private static String KEY_SCHOOL = "school";
	private static String KEY_BIRTH = "birth";
	private static String KEY_USER_ID = "userId";
	private static String KEY_TEACHER_ID = "teacherId";
	private static String KEY_STUDENT_ID = "studentId";
	private static String CSRFTOKEN = "csrftoken";

	public LoginSAO(Context context, String userName, String passWord) {
		super();
		this.url = Url.getURLLogin();
		this.userName = userName;
		this.passWord = passWord;
		this.context = context;
	}

	public void getUserFromServer() {
		JSONObject json = loginUser();
		assignSuccess(json);
		if (success) {
			createUser(json);
			// if user is teacher
			try {
				if (json.getJSONObject("user").getInt("type") == 3) {
					// Luu giang day cac lop
					saveTeachingClass(json.getJSONArray("teachingClass"));
				}
			} catch (Exception e) {
				Log.e("log error", "error when get type");
			}
		}
	}

	private void saveTeachingClass(JSONArray jsArray) {
		try {
			int size = jsArray.length();
			for (int i = 0; i < size; i++) {
				JSONObject js = jsArray.getJSONObject(i);

			}
		} catch (Exception e) {
			Log.e("log error", "error when get type");
		}
	}

	private void createUser(JSONObject json) {
		Log.d("LOG", "step 2.3.1");
		CreateDatabase db = new CreateDatabase(context);
		AccountDAO accountDAO = new AccountDAO(db.open());
		accountDAO.delete();
		try {
			JSONObject js = json.getJSONObject("user");
			if (js.getInt(KEY_TYPE) == 1) {
				accountDAO.insert(js.getString(KEY_LAST_NAME),
						js.getString(KEY_FIRST_NAME), userName,
						js.getString(KEY_TYPE), js.getString(KEY_CLASS),
						js.getString(KEY_SCHOOL), js.getString(KEY_BIRTH),
						js.getString(KEY_USER_ID),
						js.getString(KEY_STUDENT_ID), js.getString(CSRFTOKEN));
				Log.d("LOG", "added student");
			} else {
				accountDAO.insert(js.getString(KEY_LAST_NAME),
						js.getString(KEY_FIRST_NAME), userName,
						js.getString(KEY_TYPE), js.getString(KEY_CLASS),
						js.getString(KEY_SCHOOL), js.getString(KEY_BIRTH),
						js.getString(KEY_USER_ID),
						js.getString(KEY_TEACHER_ID), js.getString(CSRFTOKEN));
				Log.d("LOG", "added teacher");
			}
			db.close();
		} catch (JSONException e) {
			Log.d("LOG", e.toString());
			e.printStackTrace();
		}
	}

	private void assignSuccess(JSONObject json) {
		try {
			if ("1".equals(json.getString(KEY_SUCCESS)))
				success = true;
			else
				success = false;
		} catch (JSONException e) {
			Log.d("log error", "error when get key success");
			success = false;
			e.printStackTrace();
		}

	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWork() {
		return passWord;
	}

	public void setPassWork(String passWord) {
		this.passWord = passWord;
	}

	public JSONObject loginUser() {
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", userName));
			params.add(new BasicNameValuePair("password", passWord));
			csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(url);

			params.add(new BasicNameValuePair("csrfmiddlewaretoken",
					csrfmiddlewaretoken));
			JSONObject json = utils.getJSONObjectByHttpPost(context, url,
					params);
			if (json.getString("success").equals("1"))
				json.getJSONObject("user")
						.put("csrftoken", csrfmiddlewaretoken);
			return json;
		} catch (Exception e) {
			Log.e("log error", e.toString());
		}
		return null;
	}

	public boolean isSuccess() {
		return success;
	}
}
